<template>
  <el-dialog
    :model-value="visible"
    width="440px"
    :show-close="false"
    class="auth-modal themed"
    append-to-body
    @close="handleClose"
  >
    <template #header>
      <div class="auth-modal__header">
        <h3 class="title">{{ modeTitle }}</h3>
        <el-button text circle size="small" class="close-btn" @click="handleClose">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </template>

    <div class="panel">
      <transition name="fade-slide" mode="out-in">
        <div :key="mode">
          <!-- 登录 -->
          <div v-if="mode==='login'" class="form-wrap">
            <el-form @keyup.enter.native="onLogin" :model="loginForm" :disabled="loading.login" label-position="top">
              <el-form-item label="用户名">
                <el-input v-model="loginForm.username" placeholder="输入用户名" autocomplete="username" />
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="loginForm.password" type="password" placeholder="输入密码" autocomplete="current-password" />
              </el-form-item>
              <el-button class="primary-btn" :loading="loading.login" @click="onLogin">登录</el-button>
            </el-form>
            <div class="alt-links">
              <span>还没有账号？ <el-link type="primary" @click="switchMode('register')">注册</el-link></span>
              <span>快速体验？ <el-link type="danger" @click="switchMode('guest')">游客进入</el-link></span>
            </div>
          </div>

          <!-- 注册 -->
          <div v-else-if="mode==='register'" class="form-wrap">
            <el-form @keyup.enter.native="onRegister" :model="registerForm" :disabled="loading.register" label-position="top">
              <el-form-item label="用户名">
                <el-input v-model="registerForm.username" placeholder="设置用户名" />
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="registerForm.password" type="password" placeholder="设置密码" />
              </el-form-item>
              <el-form-item label="确认密码">
                <el-input v-model="registerForm.confirm" type="password" placeholder="再次输入" />
              </el-form-item>
              <el-button class="primary-btn alt" :loading="loading.register" @click="onRegister">注册并继续</el-button>
            </el-form>
            <div class="alt-links">
              <span>已有账号？ <el-link type="primary" @click="switchMode('login')">登录</el-link></span>
              <span>不想注册？ <el-link type="danger" @click="switchMode('guest')">游客进入</el-link></span>
            </div>
          </div>

          <!-- 游客 -->
          <div v-else class="form-wrap guest-mode">
            <div class="guest-intro">
              <p>以 <strong>游客模式</strong> 体验核心功能（进度与个性化保存受限）。</p>
            </div>
            <el-button class="primary-btn ghost" :loading="loading.guest" @click="onGuest">一键游客进入</el-button>
            <div class="alt-links">
              <span>需要完整体验？ <el-link type="primary" @click="switchMode('register')">注册账号</el-link></span>
              <span>已有账号？ <el-link type="success" @click="switchMode('login')">登录</el-link></span>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import api, { authApi } from '@/api/http'
import { STORAGE_TOKEN_KEY, setToken, getToken, authHeader } from '@/utils/auth'

const props = defineProps({
  visible: { type: Boolean, default: false }
})
const emit = defineEmits(['close', 'login-success'])

// 状态
const mode = ref('login') // login | register | guest
const loginForm = ref({ username: '', password: '' })
const registerForm = ref({ username: '', password: '', confirm: '' })
const loading = ref({ login: false, register: false, guest: false })

const modeTitle = computed(() => ({
  login: '账号登录',
  register: '注册新账号',
  guest: '游客快速体验'
})[mode.value])


const storeToken = (tk) => setToken(tk)

const fetchUser = async () => {
  // 注意：baseURL 已经是 /api，这里不能再写 /api/auth/me 否则会变成 /api/api/auth/me
  try {
    const res = await authApi.me()
    return res.data
  } catch (e) {
    return null
  }
}

const resetForms = () => {
  loginForm.value = { username: '', password: '' }
  registerForm.value = { username: '', password: '', confirm: '' }
}

const handleClose = () => {
  resetForms()
  mode.value = 'login'
  emit('close')
}

const switchMode = (m) => { mode.value = m }

const onLogin = async () => {
  if (!loginForm.value.username || !loginForm.value.password) {
    ElMessage.warning('请输入用户名与密码')
    return
  }
  loading.value.login = true
  try {
  const res = await authApi.login(loginForm.value)
    storeToken(res.data.access_token)
    ElMessage.success('登录成功')
    const user = await fetchUser()
    emit('login-success', user)
    handleClose()
  } catch (e) {
    ElMessage.error(e.response?.data?.detail || '登录失败')
  } finally {
    loading.value.login = false
  }
}

const onRegister = async () => {
  if (!registerForm.value.username || !registerForm.value.password) {
    ElMessage.warning('请输入用户名与密码')
    return
  }
  if (registerForm.value.password !== registerForm.value.confirm) {
    ElMessage.warning('两次密码不一致')
    return
  }
  loading.value.register = true
  try {
  await authApi.register({
      username: registerForm.value.username,
      password: registerForm.value.password
    })
    ElMessage.success('注册成功，已自动切换登录')
    mode.value = 'login'
    loginForm.value.username = registerForm.value.username
    loginForm.value.password = registerForm.value.password
  } catch (e) {
    ElMessage.error(e.response?.data?.detail || '注册失败')
  } finally {
    loading.value.register = false
  }
}

const onGuest = async () => {
  loading.value.guest = true
  try {
  const res = await authApi.guest()
    storeToken(res.data.access_token)
    ElMessage.success(`游客登录：${res.data.username}`)
    const user = await fetchUser()
    emit('login-success', user)
    handleClose()
  } catch (e) {
    ElMessage.error(e.response?.data?.detail || '游客登录失败')
  } finally {
    loading.value.guest = false
  }
}

watch(() => props.visible, (v) => { if (!v) resetForms(); else mode.value = 'login' })
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';

.auth-modal.themed :deep(.el-dialog__header) { margin:0; padding: 14px 18px 4px; }
.auth-modal.themed :deep(.el-dialog__body) { padding: 4px 22px 26px; }
.auth-modal.themed :deep(.el-dialog) { border-radius: 26px; overflow:hidden; background:
  linear-gradient(145deg, rgba(255,255,255,0.82), rgba(255,255,255,0.72)),
  radial-gradient(circle at 85% 15%, rgba(244,162,97,0.35), transparent 60%),
  radial-gradient(circle at 12% 85%, rgba(200,16,46,0.25), transparent 65%);
  backdrop-filter: blur(18px) saturate(180%);
  border:1px solid rgba(200,16,46,0.25);
  box-shadow: 0 18px 40px -10px rgba(0,0,0,0.25), 0 0 0 1px rgba(255,255,255,0.4) inset;
}

.auth-modal__header { display:flex; align-items:center; justify-content:space-between; }
.title { font-size:1.1rem; font-weight:600; letter-spacing:.5px; background:linear-gradient(100deg,#c8102e,#e8576b,#f4a261); -webkit-background-clip:text; background-clip:text; color:transparent; }
.close-btn { transition: all .3s; }
.close-btn:hover { background: rgba(255,255,255,0.6); }

.panel { position:relative; }
.form-wrap { width:100%; max-width:340px; margin: 0 auto; display:flex; flex-direction:column; }
.guest-mode { text-align:center; }

.primary-btn { width:100%; height:44px; font-weight:600; letter-spacing:.5px; background:linear-gradient(120deg,#c8102e,#e8576b 45%,#f4a261); color:#fff; border:none; border-radius:14px; box-shadow:0 4px 14px -4px rgba(200,16,46,0.5); }
.primary-btn:hover { filter:brightness(1.05); }
.primary-btn.alt { background:linear-gradient(120deg,#e8576b,#c8102e 50%,#e76f51); }
.primary-btn.ghost { background:linear-gradient(110deg,#264653,#2a5460); }

.alt-links { margin-top:20px; display:flex; flex-direction:column; gap:6px; font-size:.75rem; letter-spacing:.05em; text-align:center; color:$text-secondary; }
.alt-links span { opacity:.9; }

.guest-intro { font-size:.85rem; line-height:1.6; color:$text-secondary; margin: 8px 0 24px; }
.guest-intro strong { color:#c8102e; }

/* 过渡 */
.fade-slide-enter-active, .fade-slide-leave-active { transition: all .35s $ease-in-out; }
.fade-slide-enter-from { opacity:0; transform: translateY(8px); }
.fade-slide-leave-to { opacity:0; transform: translateY(-6px); }

/* Label 微调 */
:deep(.el-form-item__label) { font-weight:500; letter-spacing:.5px; color:#333; }
:deep(.el-input__wrapper) { border-radius: 12px; }
</style>
